package network;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class InetAddressEx extends JFrame {

	private JPanel contentPane;
	private JPanel panel;
	private JButton btnAddr;
	private JTextField addIn;
	private JScrollPane scrollPane;
	private JTextArea result;
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					InetAddressEx frame = new InetAddressEx();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public void getIp(){
		String d = addIn.getText();
		try{
			InetAddress[] ia = InetAddress.getAllByName(d);
			
			for(int i=0;i<ia.length;i++){
				String ip = ia[i].getHostAddress();
				result.append("[" + (i+1) + "]"+d+" 's IP : " + ip + "\n");
			}
			
		}catch(UnknownHostException ex){
			JOptionPane.showMessageDialog(null, ex.getMessage());
		}
	}
	
	public InetAddressEx() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 690, 501);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getScrollPane(), BorderLayout.CENTER);
	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getBtnAddr(), BorderLayout.EAST);
			panel.add(getAddIn(), BorderLayout.CENTER);
		}
		return panel;
	}
	private JButton getBtnAddr() {
		if (btnAddr == null) {
			btnAddr = new JButton("Get IP Address");
			btnAddr.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					getIp();
					
					
				}
			});
		}
		return btnAddr;
	}
	
	private JTextField getAddIn() {
		if (addIn == null) {
			addIn = new JTextField();
			addIn.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					int a = e.getKeyCode();
					if(a == e.VK_ENTER){
						getIp();
					}
				}
			});
			addIn.setColumns(10);
		}
		return addIn;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}
	private JTextArea getResult() {
		if (result == null) {
			result = new JTextArea();
		}
		return result;
	}
}
